package main

import (
	"errors"
	"fmt"
	"mime/multipart"
	"net/http"

	"algo-sdk-go/common/tools/excel"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, world!")
}

func main() {
	http.HandleFunc("/", helloHandler)
	http.HandleFunc("/excel/handler", ExcelHandler)
	fmt.Println("Server started on port 8080")
	http.ListenAndServe(":8080", nil)
}

func ExcelHandler(w http.ResponseWriter, r *http.Request) {
	var req ExcelHandlerRequest
	if err := httpx.Parse(r, &req); err != nil {
		httpx.Error(w, err)
		return
	}
	if len(r.MultipartForm.File) == 0 {
		fmt.Println("文件为空")
		//httpx.Error(w, errorx.NewDefaultError("文件为空"))
		return
	}
	err := ExcelImport(r.MultipartForm)
	if err != nil {
		fmt.Println(err.Error())
	}
}

func ExcelImport(MultipartForm *multipart.Form) error {
	data, err := ParseExcelData(MultipartForm)
	if err != nil {
		return err
	}
	fmt.Println(data)
	return nil
}

var (
	ExcelRawBeginIndex = 1
)

func ParseExcelData(MultipartForm *multipart.Form) (dataMap []map[int]string, err error) {
	var (
		excelContent [][]string
	)

	fileHeader := MultipartForm.File["file"][0]
	if excelContent, err = excel.AnalyzeExcel(fileHeader, "sheet_name"); err != nil {
		return nil, errors.New("解析页签失败")
	}
	if dataMap, err = excel.GetDataMap(excelContent, ExcelRawBeginIndex); err != nil {
		return nil, errors.New("解析excel数据失败")
	}
	if len(dataMap) == 0 {
		return nil, errors.New("excel数据为空")
	}

	return
}

type ExcelHandlerRequest struct {
}
